package com.commerce.recording.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;


import com.commerce.recording.R;
import com.commerce.recording.entity.Record;
import com.commerce.recording.entity.Sign;
import com.commerce.recording.utils.FormatDate;

import org.litepal.LitePal;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



public class RecordService extends Service {


    private String mFileName;
    private  MediaRecorder mRecorder;
    private long mStartingTimeMillis;
    private long mElapsedMillis;
    private static final String TAG = "Recording";
    private String format;
    private DownloadBinder binder;
    private String fileUri;
    private Record record = new Record();
    private List<Sign> listSign = new  ArrayList<>();
    private Sign sign = new Sign();
    private SharedPreferences sp_name_audio;

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        startRecording();
        return START_STICKY;
    }
    @Override
    public void onDestroy(){

        super.onDestroy();
    }


    public class DownloadBinder extends Binder{
        public Record nullRecording(){
            //停止录音
            mRecorder.stop();
            String time = new FormatDate().toHHmmssS(mElapsedMillis);
            //存入数据库
            record.setName(format);
            record.setPath(fileUri);
            record.setTime(time);
            LitePal.saveAll(listSign);
            listSign.clear();
            //释放空间
            mRecorder.release();
            mRecorder =null;
            return record;
        }
        // 标记录音
        public List<Sign> sginRecording(){
            long mElapsedMillisclone = (System.currentTimeMillis() - mStartingTimeMillis) + mElapsedMillis;
            listSign.add(0,new Sign(fileUri,mElapsedMillisclone));
            return listSign;
        }

        // 暂停录音
        @RequiresApi(api = Build.VERSION_CODES.N)
        public void stopRecording(){
            mElapsedMillis +=(System.currentTimeMillis()- mStartingTimeMillis);
            mRecorder.pause();
        }

        //继续录音
        @RequiresApi(api = Build.VERSION_CODES.N)
        public void startRecording(){
            mStartingTimeMillis =System.currentTimeMillis();
            mRecorder.resume();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        binder =new DownloadBinder();
        return binder;
    }

    // 开始录音
    private void startRecording(){
        sp_name_audio = getSharedPreferences("sp_name_audio", MODE_PRIVATE);
        setFileNameAndPath();
        mRecorder =new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置要用于录制的音频源
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//录音文件保存的格式，这里保存为 mp4(音频、视频格式)
        mRecorder.setOutputFile(fileUri);// 设置录音文件的保存路径
        Log.d("TAG", "startRecording: " +fileUri);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//设置要用于录制的音频编码器
        mRecorder.setAudioChannels(1);//设置要录制的音频频道数
        mRecorder.setAudioSamplingRate(44100);//设置录制的音频采样率
        int anInt = sp_name_audio.getInt("BitRate", 1);
        int[] intArray = getResources().getIntArray(R.array.format);// 设置录音文件的清晰度
        mRecorder.setAudioEncodingBitRate(intArray[anInt]);
        try {
            mRecorder.prepare();//准备记录器开始捕获和编码数据
        } catch (IOException|IllegalStateException e) {
            e.printStackTrace();
        }
        mRecorder.start(); //开始将数据捕获并编码到使用setOutputFile()指定的文件中
        mStartingTimeMillis =System.currentTimeMillis();
}
    // 设置录音文件的名字和保存路径
    private void setFileNameAndPath() {
        //录音默认名称
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        int anInt = sp_name_audio.getInt("Suffix", 1);
        String[] StringArray = getResources().getStringArray(R.array.format_suffix);// 设置录音文件的清晰度
        format = simpleDateFormat.format(new Date());
        mFileName = (System.currentTimeMillis())+"."+StringArray[anInt];
        fileUri = getExternalFilesDir(Environment.DIRECTORY_MUSIC).getPath() + "/" + mFileName;
    }


}
